﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GoldManager : MonoBehaviour
{
    List<GameObject> CoinList = new List<GameObject>();

    List<GameObject> FlyCoinList = new List<GameObject>();
    List<GameObject> EnemyCoinList = new List<GameObject>();

    public void Awake()
    {
        if (GameObject.FindGameObjectsWithTag("Gold").Length > 1)
        {
            Destroy(this.gameObject);
        }
        else
        {
            DontDestroyOnLoad(this.gameObject);
        }
    }

    private static GoldManager instance;
    
    public static GoldManager Instance
    {
        get
        {
            if (instance == null)
            {
                instance = GameObject.Find("Gold").GetComponent<GoldManager>();
            }
            return instance;
        }
    }
    /// <summary>
    /// 气球怪
    /// </summary>
    /// <param name="pos"></param>
    /// <param name="GoldNum"></param>
    /// <param name="parent"></param>
    public void EnemyGoldExpolde(Vector3 pos,int GoldNum,Transform parent)
    {
        for (int i = 0; i < GoldNum; i++)
        {
            CreateCoin(pos,parent);
        }
    }
    /// <summary>
    /// 飞行怪
    /// </summary>
    /// <param name="pos"></param>
    /// <param name="GoldNum"></param>
    /// <param name="parent"></param>
    public void GoldBoxExpolde(Vector3 pos, int GoldNum,Transform parent)
    {
        for(int i = 0; i < GoldNum; i++)
        {
            CreateCoin(pos,parent);
        }      
    }

    void CreateCoin(Vector3 pos,Transform parent)
    {
        GameObject obj = GetCoinFromList();
        if(obj == null)
        {
            obj = Instantiate(Resources.Load<GameObject>("Coin/Coin"));
            CoinList.Add(obj);           
        }
        if (parent.name != "FlyEnemy")
        {
            obj.GetComponent<CoinComponent>().CoinSetParent(parent);
            obj.transform.position = new Vector2(pos.x + Random.Range(50, 150), pos.y + Random.Range(50, 150));
        }
        else
        {
            obj.GetComponent<CoinComponent>().CoinSetParent(parent);
            obj.transform.position = new Vector2(pos.x + Random.Range(-200, 200), pos.y + Random.Range(-200, 200));
        }
        obj.SetActive(true);   
    }

    GameObject GetCoinFromList()
    {
        foreach(GameObject obj in CoinList)
        {
            if(!obj.activeInHierarchy)
            {
                return obj;
            }
        }
        return null;
    }
    
}
